<template>
  <div class="mastery-point-detail">
    <header class="header">
      <div v-if="showClose" @click="emit('close')" class="btn-back"></div>
      知识点：{{ sidebarData?.name }}
    </header>
    <section class="section">
      <p class="title">知识点掌握度</p>
      <div
        class="mastery-progress"
        :class="{ 'is-personal': route.query.studentId }"
      >
        <div class="mastery-progress-item">
          <CircleProgress
            :progress="
              parseFloat(
                ((sidebarData.mastery_rate.class_rate || 0) * 100).toFixed(2)
              )
            "
          />
          <span>班级掌握度</span>
        </div>
        <div class="mastery-progress-item" v-if="route.query.studentId">
          <CircleProgress
            :progress="
              parseFloat(
                ((sidebarData.mastery_rate.personal_rate || 0) * 100).toFixed(2)
              )
            "
          />
          <span>个人掌握度</span>
        </div>
        <div v-else class="mastery-progress-item">
          <CircleProgress
            :progress="
              parseFloat(
                ((sidebarData.mastery_rate.grade_rate || 0) * 100).toFixed(2)
              )
            "
          />
          <span>年级掌握度</span>
        </div>
      </div>
    </section>
    <template v-if="!route.query.studentId">
      <section class="section mastery-publish">
        <p class="title">掌握度分布</p>
        <div class="column-wrapper">
          <div class="column" v-for="item in MASTERY" :key="item.name">
            <p class="num">{{ differList[item.key].length }}人</p>
            <div class="col-bg">
              <div
                class="content"
                :style="{
                  'background-color': item.color,
                  height: `${studentList.length ? (differList[item.key].length / studentList.length) * 100 : 0}%`
                }"
              ></div>
            </div>
            <p class="name">{{ item.name }}</p>
          </div>
        </div>
      </section>
      <section class="section">
        <p class="title">分布名单</p>
        <ul class="tab">
          <li
            class="tab-item"
            v-for="(item, index) in MASTERY"
            :class="{ active: currentLevel === index }"
            :key="item.name"
            @click="currentLevel = index"
          >
            {{ item.name }}
          </li>
        </ul>
        <template v-if="differList[MASTERY[currentLevel].key].length">
          <ul class="student-list">
            <li
              class="student-list-item"
              v-for="student in differList[MASTERY[currentLevel].key]"
              :key="student.student_id"
              @click="goPersonMastery(student)"
            >
              <p class="student-name">{{ student.student_name }}</p>
              <div class="student-data">
                <label class="rate"
                  >{{ parseFloat((student.rate * 100).toFixed(2)) }}%</label
                >
                <div class="progress">
                  <p
                    class="data"
                    :style="{ width: `${student.rate * 100}%` }"
                  ></p>
                </div>
              </div>
            </li>
          </ul>
        </template>
        <el-empty v-else></el-empty>
      </section>
    </template>

    <student-status
      currentTab="mastery-level"
      :currentGradeNum="currentGradeNum"
      :knowledgeId="sidebarData.id"
      :classId="classId"
      :selectTime="selectTime"
      @toDetail="toDetail"
    />
    <div class="to-detail">
      <button @click="toDetail" class="btn-detail">靶向提升</button>
    </div>
  </div>
</template>
<script setup>
import CircleProgress from './CircleProcess.vue'
import StudentStatus from './StudentStatus.vue'
import { getMasteryRank } from '@/apis/target-boost/index.js'
import { useAuthStore, useKnowledgeStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive, watch } from 'vue'
import dayjs from 'dayjs'

const knowledgeStore = useKnowledgeStore()
const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()

const MASTERY = [
  {
    name: '优秀',
    color: '#6CD999',
    key: 'excellent'
  },
  {
    name: '良好',
    color: '#78BEFF',
    key: 'good'
  },
  {
    name: '一般',
    color: '#FFD07D',
    key: 'general'
  },
  {
    name: '较差',
    color: '#FF918B',
    key: 'bad'
  }
]

const progressColor = [
  {
    color: '#76B3FF',
    percentage: 0
  },
  {
    color: '#7DBFFF',
    percentage: 46.98
  },
  {
    color: '#84CBFF',
    percentage: 93.18
  }
]

const props = defineProps({
  showClose: Boolean,
  classId: String,
  currentGradeNum: Number,
  subjectId: Number,
  currentTab: String,
  selectTime: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['close', 'go-personal-mastery'])
const sidebarData = defineModel('sidebarData')

const currentLevel = ref(0)
// 学生列表
const studentList = ref([])
const differList = reactive({
  excellent: [],
  good: [],
  general: [],
  bad: []
})
const getStudentsData = async () => {
  const { data } = await getMasteryRank({
    school_id: authStore.userInfo.school_id,
    class_id: props.classId || route.query.class_id,
    class_type: +route.query.class_type || authStore.classType,
    subject_id: +route.query.subject_id || authStore.nowGlobalSubjectId,
    grade_id: props.currentGradeNum || +route.query.grade_num,
    knowledge_id: sidebarData.value.id
  })
  studentList.value = data || []
  handleStudentList()
}

const handleStudentList = () => {
  differList.excellent = []
  differList.good = []
  differList.general = []
  differList.bad = []
  for (let index = 0; index < studentList.value.length; index++) {
    const element = studentList.value[index]
    const rate = element.rate
    if (element.is_learn) {
      if (rate >= 0.95) {
        differList.excellent.push(element)
      } else if (rate >= 0.75) {
        differList.good.push(element)
      } else if (rate >= 0.6) {
        differList.general.push(element)
      } else {
        differList.bad.push(element)
      }
    }
  }
}

watch(
  () => sidebarData.value,
  () => {
    console.log('sidebarData', sidebarData)
    getStudentsData()
  },
  {
    immediate: true,
    deep: true
  }
)

const goPersonMastery = student => {
  const params = {
    studentId: student.student_id,
    studentName: student.student_name,
    mode: 'mastery-level',
    start_time: props.selectTime?.[0] || dayjs('2021-01-01').unix(),
    end_time: props.selectTime?.[1] || dayjs().unix(),
    class_type: +route.query.class_type || authStore.classType,
    grade_num: props.currentGradeNum || +route.query.grade_num,
    subject_id: +route.query.subject_id || authStore.nowGlobalSubjectId,
    class_id: props.classId || route.query.class_id,
    compare: 0
  }
  const newRoute = router.resolve({
    name: 'student-graph-analyze',
    query: params
  })
  window.open(newRoute.href, '_blank')
}

const toDetail = (_, record) => {
  knowledgeStore.setKnowledgeTree(sidebarData.value)
  console.log(record)
  emit('toDetail', record)
}
</script>
<style lang="less" scoped>
.mastery-point-detail {
  background-color: #fff;
  min-height: 90vh;
  padding: 20px 20px 0 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .header {
    display: flex;
    gap: 10px;
    align-items: center;
    color: rgba(4, 11, 26, 0.9);
    font-weight: 700;
    font-size: 18px;
    margin-bottom: 18px;

    .btn-back {
      flex-shrink: 0;
      margin-right: 10px;
      width: 16px;
      height: 14px;
      background-image: url(@/assets/images/target-boost/icon-back.svg);
      background-size: cover;
      cursor: pointer;
    }
  }

  .section {
    margin-bottom: 28px;

    .el-empty {
      padding: unset;
    }

    .title {
      position: relative;
      padding-left: 20px;
      font-size: 16px;
      font-weight: 500;
      color: #040b1ae5;
      margin-bottom: 20px;

      &::before {
        position: absolute;
        content: '';
        background-color: @color-brand-regular;
        width: 7px;
        height: 17px;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .tab {
      width: fit-content;
      display: flex;
      border: 1px solid #b4b6ba;
      padding: 1px;
      border-radius: 4px;

      &-item {
        cursor: pointer;
        padding: 5px 11px;
        border-radius: 4px;
        color: #040b1ab2;
        font-size: 12px;
        transition: 0.3s;

        &.active {
          background-color: @color-brand-regular;
          color: #fff;
          font-weight: 500;
        }
      }
    }

    .student-list {
      margin-bottom: unset;

      &-item {
        &:not(:last-child) {
          margin-bottom: 12px;
        }

        cursor: pointer;
      }

      .student-name {
        color: rgba(4, 11, 26, 0.6);
        margin-bottom: 6px;
        font-size: 14px;
      }

      .student-data {
        display: flex;
        gap: 11px;

        .rate {
          display: inline-block;
          height: 23px;
          width: 49px;
          line-height: 24px;
          background-color: #7ec8fe;
          text-align: center;
          border-radius: 6.4px;
          font-size: 13px;
          font-weight: 900;
          color: #fff;
        }

        .progress {
          flex: 1;
          position: relative;
          height: 24px;
          width: 100%;
          background-color: #f0f6ff;
          border-radius: 6.4px;
          overflow: hidden;

          .data {
            position: absolute;
            left: 0;
            height: 100%;
            background-color: #7ec8fe;
            border-radius: 6.4px;
            transition: 0.3s ease-in-out;
          }
        }
      }
    }
  }

  .mastery-progress {
    display: flex;
    justify-content: space-between;
    gap: 20px;

    &.is-personal {
      flex-direction: row-reverse;
    }

    &-item {
      width: 130px;
      display: flex;
      flex-direction: column;
      justify-items: center;
      text-align: center;
      gap: 4px;

      span {
        font-size: 14px;
        color: rgba(4, 11, 26, 0.7);
      }

      .percentage-value {
        font-size: 20px;
        font-weight: 700;
        color: @color-brand-regular;
      }
    }
  }

  .mastery-publish {
    .column-wrapper {
      display: flex;
      justify-content: space-between;
    }

    .column {
      width: 40px;

      .num {
        text-align: center;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0px 1px 5px 0px #00000026;
        margin-bottom: 10px;
        color: #040b1ab2;
        font-size: 11px;
        padding: 3px 0;
      }

      .col-bg {
        position: relative;
        background-color: #f0f6ff;
        border-radius: 10px 10px 0 0;
        width: 100%;
        height: 105px;
      }

      .content {
        transition: 0.3s ease-in-out;
        position: absolute;
        border-radius: 10px 10px 0 0;
        width: 100%;
        bottom: 0;
      }

      .name {
        margin-top: 6px;
        text-align: center;
        font-size: 14px;
        color: rgba(4, 11, 26, 0.6);
      }
    }
  }

  .to-detail {
    margin-top: auto;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-sizing: border-box;
    position: sticky;
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #fff;
    box-shadow: inset 0 1px #f0f0f0;
    line-height: 60px;
    text-align: right;
    z-index: 100;

    .btn-detail {
      border: 0;
      padding: 0 12px;
      background-color: @color-brand-regular;
      line-height: 2;
      font-size: 16px;
      color: #fff;
      cursor: pointer;
      border-radius: 5px;
    }
  }
}
</style>
